#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

from common.cleaner import clear
from hcs.gaussdb.common.const import EnvName
from hcs.gaussdb.common.gaussdb_common import get_std_in_variable
from hcs.gaussdb.common.gaussdb_restful import request_post


class HcsManagerAbility:
    @staticmethod
    def get_tokens_json(pid, project_domain, project_name, addr):
        token_body = {
            "auth": {
                "identity": {
                    "methods": ["password"],
                    "password": {"user": {"name": "", "password": "", "domain": {"name": ""}}}
                },
                "scope": {"project": {"name": "", "domain": {"name": ""}}}
            }
        }
        token_header = {'Content-Type': 'application/json'}
        # 待确定管控面端口是否固定
        url = f"{addr}/v3/auth/tokens"
        user_name = get_std_in_variable(f"{EnvName.IAM_USERNAME}_{pid}")
        user_password = get_std_in_variable(f"{EnvName.IAM_PASSWORD}_{pid}")
        try:
            token_body["auth"]["identity"]["password"]["user"]["name"] = user_name
            token_body["auth"]["identity"]["password"]["user"]["password"] = user_password
            token_body["auth"]["identity"]["password"]["user"]["domain"]["name"] = project_domain
            token_body["auth"]["scope"]["project"]["name"] = project_name
            token_body["auth"]["scope"]["project"]["domain"]["name"] = project_domain
        except KeyError as err:
            raise Exception(f"Failed to get correct key from the dict") from err
        ret, body, header = request_post(url, token_body, token_header)
        clear(user_password)
        return ret, body, header
